<template>
    <div class="app-container add">
        <CommonHeader :title="title" :isShowBack="true" backUrl="/productInventory"/>
        <div class="add-wrap">
            <div class="form-box">
                <div class="form-title">基本信息</div>
                <el-form :model="formData" ref="formData" :rules="rules" inline-message label-width="0" label-position="left">
                    <el-form-item prop="orderNumber">
                        <div class="form-item">
                            <div class="label"><span class="required"></span>入库单号</div>
                            <div class="select-wrap">
                                <van-field v-model="formData.orderNumber" input-align="right" placeholder="输入入库单号" label=""/>
                            </div>
                        </div>
                    </el-form-item>
                    <el-form-item prop="relateType">
                        <div class="form-item">
                            <div class="label"><span class="required"></span>关联单据类型</div>
                            <div class="select-wrap" @click="relateModalShow = true">
                                <span class="val" v-if="formData.relateType">{{ formData.relateTypeName }}</span>
                                <span class="txt" v-else>请选择</span>
                                <i class="el-icon-arrow-down down-icon"></i>
                            </div>
                        </div>
                    </el-form-item>
                    <el-form-item prop="relateOrders">
                        <div class="form-item">
                            <div class="label">
                                <span class="required"></span>单号选择<img src="@/assets/images/scan02.png" alt="" class="scan" @click.stop="handleScanCode">
                            </div>
                            <div class="select-wrap" @click="relateOrderChange">
                                <span class="val" v-if="formData.relateOrders">{{ formData.relateOrders }}</span>
                                <span class="txt" v-else>请选择</span>
                                <i class="el-icon-arrow-down down-icon"></i>
                            </div>
                        </div>
                    </el-form-item>
                    <el-form-item prop="planTime">
                        <div class="form-item">
                            <div class="label"><span class="required"></span>计划入库日期</div>
                            <div class="select-wrap" @click="planTimeChange">
                                <span class="val" v-if="formData.planTime">{{ formData.planTime }}</span>
                                <span class="txt" v-else>请选择</span>
                                <i class="el-icon-arrow-down down-icon"></i>
                            </div>
                        </div>
                    </el-form-item>
                    <el-form-item prop="applyPerson">
                        <div class="form-item">
                            <div class="label"><span class="required"></span>申请人</div>
                            <div class="select-wrap" @click="applyPersonChange">
                                <span class="val" v-if="formData.nickname">{{ formData.nickname }}</span>
                                <span class="txt" v-else>请选择</span>
                                <i class="el-icon-arrow-down down-icon"></i>
                            </div>
                        </div>
                    </el-form-item>
                    <el-form-item prop="packagePerson">
                        <div class="form-item">
                            <div class="label">包装员</div>
                            <div class="select-wrap" @click="packagePersonChange">
                                <span class="val" v-if="formData.packagePerson">{{ formData.packagePerson }}</span>
                                <span class="txt" v-else>请选择</span>
                                <i class="el-icon-arrow-down down-icon"></i>
                            </div>
                        </div>
                    </el-form-item>
                    <el-form-item prop="inspection">
                        <div class="form-item">
                            <div class="label">全检员</div>
                            <div class="select-wrap" @click="inspectionChange">
                                <span class="val" v-if="formData.inspection">{{ formData.inspection }}</span>
                                <span class="txt" v-else>请选择</span>
                                <i class="el-icon-arrow-down down-icon"></i>
                            </div>
                        </div>
                    </el-form-item>
                </el-form>
            </div>
            <!-- 物料信息 -->
            <div class="material-box">
                <div class="item-title">物料信息</div>
                <div class="box-content">
                    <template v-if="productWorkOrderMaterialInfo.length > 0">
                        <van-cell v-for="item,index in productWorkOrderMaterialInfo" :key="index">
                            <materia-item :singleMaterial="item" :index="index" :globalState="globalState ? 1 : 0">
                                <template slot="action">
                                    <el-button @click="printEvent(item)" :disabled="globalState">打印</el-button>
                                </template>
                            </materia-item>
                        </van-cell>
                    </template>
                    <van-empty v-else description="暂无物料信息"></van-empty>
                </div>
            </div>
        </div>
        <div class="model-footer-wrap">
            <van-button type="info" class="save-btn" block round color="#548af1" size="normal" :loading="saveLoading" @click="completeEvent('save')" :disabled="globalState">保存</van-button>
            <van-button type="primary" class="complete-btn" block round color="#548af1" size="normal" :loading="completeLoading" @click="completeEvent('complete')" :disabled="globalState">提交完成</van-button>
        </div>
        <!-- 关联单据类型 -->
        <van-popup v-model="relateModalShow" position="bottom">
            <van-picker title="关联单据类型" show-toolbar :columns="relateList" value-key="label" @confirm="relateModalConfirm" @cancel="relateModalShow = false"/>
        </van-popup>
        <!-- 时间选择 -->
        <van-calendar v-model="dateShow" @confirm="calendarConfirm" color="#548AF1"></van-calendar>
        <!-- 申请人 -->
        <van-popup v-model="applyPersonShow" position="bottom">
            <van-picker title="申请人" show-toolbar :columns="applyPersonList" value-key="nickname" @confirm="applyPersonConfirm" @cancel="applyPersonShow = false"/>
        </van-popup>
        <!-- 包装员 -->
        <van-popup v-model="packageShow" position="bottom">
            <van-picker title="包装员" show-toolbar :columns="packageList" value-key="nickname" @confirm="packageConfirm" @cancel="packageShow = false"/>
        </van-popup>
        <!-- 全检员 -->
        <van-popup v-model="inspectionShow" position="bottom">
            <van-picker title="全检员" show-toolbar :columns="inspectionList" value-key="nickname" @confirm="inspectionConfirm" @cancel="inspectionShow = false"/>
        </van-popup>
        <!-- 扫码 -->
        <img src="@/assets/images/allocation/scan.png"  v-draggable  class="scan-img" @click="scanCodeEvent"/>
        <!-- 打印 -->
        <print v-if="isPrintShow" :isShowPrint="isPrintShow" :materialInfo="printMaterialInfo" @handleConfirmPrint="handleConfirmPrint" @handleCancelPrint="handleCancelPrint"></print>
        <!--dialog 多个相同物料时弹出提示 -->
        <el-dialog title="选择物料" :visible.sync="dialogVisible" width="90%" show-close :close-on-click-modal="false">
            <el-table ref="dialogTable" :data="dialogTableList" style="width: 100%" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column prop="materialEntity.name" label="物料名称"width="120"></el-table-column>
                <el-table-column prop="materialEntity.code" label="物料编码"width="120"></el-table-column>
                <el-table-column prop="materialEntity.customFieldOne" label="物料编码"width="120"></el-table-column>
                <el-table-column prop="materialEntity.standard" label="物料规格"width="120"></el-table-column>
                <el-table-column prop="planAmount" label="计划入库数"width="120"></el-table-column>
            </el-table>
            <span slot="footer" class="dialog-footer">
                <el-button size="mini" type="primary" @click="dialogTableConfirm">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
import CommonHeader from "@/components/CommonHeader";
import MateriaItem from "./allocationDetail/components/MateriaItem.vue";
import { reqProductOrderDetail, reqWarehouseList, reqWorkOrderCompleteDetail, reqCurrentPerson, reqUserList, reqPurchaseSuppliers,reqUpdateProductOrder, reqScanCodeRuleInfo, reqBarcode,reqProductOrderCompleteDetail } from "@/api/cj_productInventory.js";
import { Toast, Dialog } from "vant";
import { mapMutations } from "vuex";
import { formatDate, analysisScanCodeRules } from "@/utils/toosls.js";
import { cloneDeep } from "lodash";
import print from "./allocationDetail/components/print.vue";
import { closeBarheight, appBarheight, appTabBarControl } from "@/utils/jingzhi.js";
import { reqPackageList, reqInspectionList } from "@/api/cj_productInventory.js";
export default {
  components: {
    CommonHeader,
    MateriaItem,
    print
  },
  data() {
    return {
        formData: {
            orderNumber:"",
            relateTypeName:"生产工单",
            relateType:"workOrder",
            relateOrders: "",
            id:"",
            state:"",
            planTime:formatDate(),
            nickname:"",
            applyPerson:"",
            personPhone:"",
            packagePerson:"",
            inspection:""
        },
        rules: {
            orderNumber:[{required:true,message:"请输入",trigger:"change"}],
            relateType:[{required:true,message:"请选择",trigger:"change"}],
            relateOrders:[{required:true,message:"请选择",trigger:"change"}],
            planTime:[{required:true,message:"请选择",trigger:"change"}],
            applyPerson:[{required:true,message:"请选择",trigger:"change"}],
            packagePerson:[{required:false,message:"请选择",trigger:"change"}],
            inspection:[{required:false,message:"请选择",trigger:"change"}]
        },
        orderNumberListShow:false,
        orderNumberList:[],
        relateModalShow: false,
        dateShow:false,
        applyPersonShow:false,
        applyPersonList:[],
        provideCompanyShow:false,
        provideCompanyList:[],
        relateList:[{label:'生产工单',value:'workOrder'},{label:'生产订单',value:'productOrder'}],
        materialList:[],
        productWorkOrderMaterialInfo:[],
        warehouseList:[],
        isPrintShow:false,
        printMaterialInfo:null,
        completeLoading:false,
        saveLoading:false,
        packageShow:false,
        inspectionShow:false,
        packageList:[],
        inspectionList:[],
        dialogVisible:false,
        dialogTableList:[],
        selectedRow:null,
        scanInfo_tmp:null
    }
  },
  mounted(){
    this.setMaterialContentHeight();
    window.addEventListener('resize',this.setMaterialContentHeight);
    // 扫码枪扫码
    const scanning_gun_enable = process.env.VUE_APP_BAR_CODE_SCANNING_GUN || false;
    if(scanning_gun_enable){
      window["ScanCodeMsg"] = (res) => {
        if (res) {
          console.log(res, "ScanCodeMsg这是首页，监听到扫码枪有结果了");
          this.scanCodeEvent2(res)
        }
      }
    }
    //cacheData
    const cacheData = this.$store.state.cjProductInventory.purchaseEditInfoCache;
    this.setCacheData(cacheData);
    const productOrderId = this.$route.query.productOrderId;
    if(productOrderId){
        this.getProductOrderDetail(productOrderId);
    }
    this.getWareHouseInfo();
    if(!productOrderId){
        this.getMaterialListByOrderNum();
    }
    this.getUserList();
    this.getPackageList();
    this.getInspectionList();
  },
  beforeDestroy(){
    // this.CLEAR_PURCHASE_EDIT_INFO_CACHE();
    console.log('详情页即将销毁...');
  },
  computed:{
    title(){
        const state = this.$route.query.state || 0;
        const t = state == 0 ? '生产入库编辑' : '生产入库详情';
        console.log('路由state参数:',state);
        return t;
    },
    globalState(){
        /**
         * 路由query参数state: 0-编辑 1-详情
         */
        const state = this.$route.query.state || 0;
        const t = state == 0 ? false : true;
        return t;
    }
  },
  methods: {
    ...mapMutations('cjProductInventory',['SET_CACHE_DEFAULT_ORDER_NUM','SET_CACHE_RELATE_ORDERS','SET_CACHE_PLAN_TIME','SET_CACHE_APPLY_PERSON','SET_CACHE_PROVIDE_COMPANY','CLEAR_PURCHASE_EDIT_INFO_CACHE','SET_CACHE_ID','SET_CACHE_STATE','set_cache_relateType','clear_cache_relateType']),
    ...mapMutations('cjProductInventory',['set_cache_inspection','set_cache_package']),
    //获取生产入库单详情
    getProductOrderDetail(purchaseId){
        reqProductOrderDetail(purchaseId).then(response => {
            if(response.code === 200){
                const { orderNumber, relateTypeName,relateType, relateOrders, planTime, applyPersonName, supplierName, materialDetails, warehouseCode,warehouseId,warehouseName, warehouseManager } = response.data;
                const { state, id, applyPerson ,personPhone,ext } = response.data;
                this.formData.orderNumber = orderNumber;
                this.formData.relateTypeName = relateTypeName;
                this.formData.relateType = relateType;
                this.formData.relateOrders = relateOrders;
                this.formData.planTime = planTime;
                this.formData.nickname = applyPersonName;
                this.formData.applyPerson = applyPerson;
                this.formData.personPhone = personPhone;
                this.formData.id = id;
                this.formData.state = state;
                this.formData.packagePerson = ext?.fieldEight;
                this.formData.inspection = ext?.fieldNine;
                const materialList = materialDetails.map(v => {
                    //批次信息
                    const batchInfoList = v.stockMaterialDetaiList || [];
                    return {
                        id:v.id,
                        checked:true,
                        materialEntity:{
                            code:v.materialFields.code,
                            name:v.materialFields.name,
                            isBatchMag:v.materialFields.isBatchMag,
                            standard:v.materialFields.standard,
                            comp:v.materialFields.comp,
                            unit:v.materialFields.unit,
                            isDoubleUnit:v.materialFields.isDoubleUnit,
                          customFieldOne:v.materialFields.customFieldOne
                        },
                        planAmount:v.planAmount,
                        actualAmount:v.actualAmount,
                        skuName:v.skuName,
                        realNum:v.actualAmount,  //实际数量
                        materialRemark:v.materialRemark,
                        supplierName:supplierName,
                        //批次列表
                        stockMaterialDetaiList:batchInfoList.map(v => {
                            return {
                                ...v,
                                checked:true
                            }
                        }),
                        isExpand:true,
                        warehouseInfo:{
                            warehouseName:warehouseName,
                            warehouseId:warehouseId,
                            warehouseCode:warehouseCode,
                            warehouseManager:warehouseManager,
                            warehouseList:this.warehouseList
                        },
                        extendMap:v.extendMap
                    }
                })
                this.productWorkOrderMaterialInfo = materialList;
                //暂存数据
                this.SET_CACHE_DEFAULT_ORDER_NUM(orderNumber);
                this.SET_CACHE_RELATE_ORDERS(relateOrders);
                this.SET_CACHE_PLAN_TIME(planTime);
                this.SET_CACHE_APPLY_PERSON({applyPerson,applyPersonName,personPhone});
                this.SET_CACHE_ID(id);
                this.SET_CACHE_STATE(state);
                this.set_cache_relateType(relateType);
                this.set_cache_package(ext?.fieldEight);
                this.set_cache_inspection(ext?.fieldNine);
            }
            console.log("获取生产入库单详情",response);
        },error => {
            Dialog.confirm({title:'提示',message:'获取生产入库单详情失败，请重试',confirmButtonText:"确定",cancelButtonText:"取消"});
            console.log("获取生产入库单详情",error);
        })
    },
    showOrderNumberListModal(){
        const relateType = this.formData.relateTypeName;
        if(!relateType){
            Dialog.alert({title:'提示',message:'请先选择关联单据类型'});
            return;
        }
        this.orderNumberListShow = true;
    },
    relateOrderChange(){
        const isExecute = this.globalState;
        if(isExecute){
            return;
        }
        const relateType = this.formData.relateType;
        const relateTypeName = this.formData.relateTypeName;
        if(!(relateType && relateTypeName)){
            Dialog.alert({title: '提示',message: "请先选择关联单据"});
            return;
        }
        if(relateType === 'workOrder'){
            this.$router.push({name:'ProductOrder',query:{from:'/productInventory/detail'}});
        } else {
            this.$router.push({name:'ProductOrder2',query:{from:'/productInventory/detail'}});
        }
    },
    planTimeChange(){
        const isExecute = this.globalState;
        if(isExecute){
            return;
        }
        this.dateShow = true;
    },
    applyPersonChange(){
        const isExecute = this.globalState;
        if(isExecute){
            return;
        }
        this.applyPersonShow = true;
    },
    packagePersonChange(){
        const isExecute = this.globalState;
        if(isExecute){
            return;
        }
        this.packageShow = true;
    },
    inspectionChange(){
        const isExecute = this.globalState;
        if(isExecute){
            return;
        }
        this.inspectionShow = true;
    },
    provideCompanyChange(){
        const isExecute = this.globalState;
        if(isExecute){
            return;
        }
        this.provideCompanyShow = true;
    },
    //单号扫码选择
    async handleScanCode() {
        if(this.globalState){
            return;
        }
        const isDevelopment = process.env.NODE_ENV === 'development';
        let relateOrders = this.formData.relateType == 'workOrder' ? "SCGD250328004" : "SCDD20250414106";
        if(!this.formData.relateType) {
            Dialog.alert({title:'提示',message:'请先选择关联单据类型'});
            return;
        }
        try {
            if(!isDevelopment){
                relateOrders = await window.flutter_inappwebview.callHandler("qrCode");
            }
            console.log("调用精致扫码api",relateOrders);
        } catch (error) {
            Dialog.alert({title:'提示',message:'当前设备不支持扫码'});
            console.log('调用精致扫码api',error);
            return;
        }
        this.formData.relateOrders = relateOrders;
        //获取物料列表信息
        this.getMaterialListByOrderNum();
    },
    relateModalConfirm(val){
        if(this.formData.relateType != val.value){
            this.formData.relateOrders = "";
            this.clear_cache_relateType();
            this.productWorkOrderMaterialInfo = [];
        }
        this.formData.relateTypeName = val.label;
        this.formData.relateType = val.value;
        this.relateModalShow = false;
        this.set_cache_relateType(val.value);
    },
    //根据选择的单号信息获取对应的物料信息
    getMaterialListByOrderNum(){
        const relateOrders = this.formData.relateOrders || this.$store.state.cjProductInventory.purchaseEditInfoCache?.relateOrders;
        if(!relateOrders){
            return;
        }
        const relateType = this.$store.state.cjProductInventory.relateType || this.formData.relateType;
        if(relateType == 'workOrder'){
            reqWorkOrderCompleteDetail(relateOrders).then(response => {
                if(response.code === 200 && response.data){
                    const { materialFields, supplierName, supplierCode, extendMap, planQuantity, finishCount } = response.data;
                    const materialInfo = {
                        checked:false,
                        materialEntity:{
                            code:materialFields.code,
                            name:materialFields.name,
                            isBatchMag:materialFields.isBatchMag,
                            standard:materialFields.standard,
                            comp:materialFields.comp,
                            unit:materialFields.unit,
                            isDoubleUnit:materialFields.isDoubleUnit,
                          customFieldOne:materialFields.customFieldOne
                        },
                        planAmount:planQuantity,
                        actualAmount:finishCount,
                        skuName:materialFields.skuEntity.skuName,
                        realNum:"",  //实际数量
                        materialRemark:materialFields.materialRemark,
                        supplierName:supplierName,
                        stockMaterialDetaiList:[],  //批次列表
                        isExpand:true,
                        warehouseInfo:{
                            warehouseName:"",
                            warehouseId:this.warehouseList.length > 0 ? this.warehouseList[0].warehouseId : "",
                            warehouseCode:"",
                            warehouseManager:"",
                            warehouseList:this.warehouseList || []
                        },
                        extendMap:{
                            zhashu:""
                        }
                    }
                    this.productWorkOrderMaterialInfo = [materialInfo];
                    this.formData.provideCompany = supplierName;
                    this.formData.provideCompanyCode = supplierCode;
                    this.formData.productWorkOrderProvideCompanyCode = supplierCode;
                    this.formData.productWorkOrderProvideCompany = supplierName;
                } else {
                    Dialog.confirm({title:'提示',message:'未获取到该单号对应物料信息，点击确定按钮重试',confirmButtonText:"确定",cancelButtonText:"取消"}).then(confirm => {
                        this.getMaterialListByOrderNum();
                    })
                }
                console.log('查询生产工单详情api',response);
            },error => {
                Dialog.confirm({title:'提示',message:'获取单号对应物料信息失败，点击确定按钮重试',confirmButtonText:"确定",cancelButtonText:"取消"}).then(confirm => {
                    this.getMaterialListByOrderNum();
                })
                console.log('查询生产工单详情api',error);
            })
        } else {
            reqProductOrderCompleteDetail(relateOrders).then(response => {
                if(response.code === 200 && response.data){
                    const { supplierName, supplierCode, extendMap, productOrderMaterials } = response.data;
                    const materialList = [];
                    for(let j = 0; j < productOrderMaterials.length; j ++){
                        const { materialFields } = productOrderMaterials[j];
                        const materialInfo = {
                            checked:false,
                            materialEntity:{
                                code:materialFields.code,
                                name:materialFields.name,
                                isBatchMag:materialFields.isBatchMag,
                                standard:materialFields.standard,
                                comp:materialFields.comp,
                                unit:materialFields.unit,
                                isDoubleUnit:materialFields.isDoubleUnit,
                                customFieldOne:materialFields.customFieldOne
                            },
                            planAmount:extendMap.completeQuantityVO.planInQuantity == "null" ? 0 : Number(extendMap.completeQuantityVO.planInQuantity),
                            actualAmount:((extendMap.completeQuantityVO.planInQuantity) == "null" ? 0 : Number(extendMap.completeQuantityVO.planInQuantity)) - (extendMap.completeQuantityVO.hadInQuantity == "null" ? 0 : Number(extendMap.completeQuantityVO.hadInQuantity)),
                            skuName:"",
                            realNum:"",  //实际数量
                            materialRemark:materialFields.materialRemark,
                            supplierName:supplierName,
                            stockMaterialDetaiList:[],  //批次列表
                            isExpand:true,
                            warehouseInfo:{
                                warehouseName:"",
                                warehouseId:this.warehouseList.length > 0 ? this.warehouseList[0].warehouseId : "",
                                warehouseCode:"",
                                warehouseManager:"",
                                warehouseList:this.warehouseList || []
                            },
                            extendMap:{
                                zhashu:""
                            }
                        }
                        materialList.push(materialInfo);
                    }
                    this.productWorkOrderMaterialInfo = materialList;
                    this.formData.provideCompany = supplierName;
                    this.formData.provideCompanyCode = supplierCode;
                    this.formData.productWorkOrderProvideCompanyCode = supplierCode;
                    this.formData.productWorkOrderProvideCompany = supplierName;
                    console.log("物料信息",materialList);
                } else {
                    Dialog.confirm({title:'提示',message:'未获取到该单号对应物料信息，点击确定按钮重试',confirmButtonText:"确定",cancelButtonText:"取消"}).then(confirm => {
                        this.getMaterialListByOrderNum();
                    })
                }
                console.log('查询生产工单详情api',response);
            },error => {
                Dialog.confirm({title:'提示',message:'获取单号对应物料信息失败，点击确定按钮重试',confirmButtonText:"确定",cancelButtonText:"取消"}).then(confirm => {
                    this.getMaterialListByOrderNum();
                })
                console.log('查询生产工单详情api',error);
            })
        }
    },
    getCurrentPerson(){
        reqCurrentPerson().then(response => {
            if(response.code === 200 && response.data){
                const { id,nickname,mobile,username } = response.data;
                this.formData.nickname = nickname;
                this.formData.applyPerson = username;
                this.formData.personPhone = mobile;
            }
            console.log('获取当前用户信息',response);
        }, error => {
            console.log('获取当前用户信息',error);
        })
    },
    getUserList(){
        reqUserList().then(response => {
            if(response.code === 200 && response.data && response.data.content){
                const tmp = response.data.content.map(v => {
                    return {
                        id:v.id,
                        username:v.username,
                        nickname:v.nickname,
                        mobile:v.mobile
                    }
                })
                this.applyPersonList = tmp;
            }
            console.log('获取申请用户列表信息',response);
        }, error => {
            console.log('获取申请用户列表信息',error);
        })
    },
    getPurchaseSuppliers(){
        reqPurchaseSuppliers().then(response => {
            if(response.code === 200 && response.data){
                const tmp = response.data.content.map(v => {
                    return {
                        code:v.code,
                        name:v.name
                    }
                })
                this.provideCompanyList = tmp;
            }
            console.log('获取供应商列表信息',response);
        }, error => {
            console.log('获取供应商列表信息',error);
        })
    },
    calendarConfirm(date){
        const D = new Date(date);
        const y = D.getFullYear();
        const m = D.getMonth() + 1;
        const d = D.getDate();
        const h = D.getHours();
        const min = D.getMinutes();
        const s = D.getSeconds();
        const f = y + "-" + (m > 9 ? m : '0' + m) + "-" + (d > 9 ? d : '0' + d) + " 00:00:00";
        this.formData.planTime = f;
        this.dateShow = false;
        this.SET_CACHE_PLAN_TIME(f);
    },
    applyPersonConfirm(person){
        const { id,username,nickname,mobile } = person;
        this.formData.nickname = nickname;
        this.formData.applyPerson = username;
        this.formData.personPhone = mobile;
        this.applyPersonShow = false;
        this.SET_CACHE_APPLY_PERSON({applyPerson:username,applyPersonName:nickname,personPhone:mobile});
    },
    provideCompanyPickerConfirm(company){
        const { code,name } = company;
        this.formData.provideCompany = name;
        this.formData.provideCompanyCode = code;
        this.provideCompanyShow = false;
        this.SET_CACHE_PROVIDE_COMPANY({supplierCode:code,supplierName:name});
    },
    async setMaterialContentHeight(){
        const dom = document.querySelector(".box-content");
        const height = window.innerHeight;
        const offsetTop = dom.offsetTop;
        const offsetLeft = dom.offsetLeft;
        dom.style.height = height - offsetTop - 70 + 'px';
        console.log('高度设置 ===>',height - offsetTop - 70 + 'px');
        //设置add-warp的padding-top
        const wrap = document.querySelector(".add-wrap");
        const isDevelopment = process.env.NODE_ENV === 'development';
        let temp = 44;
        try {
            if(!isDevelopment){
                const h = await closeBarheight();
                const l = await appBarheight();
                console.log("获取关闭按钮高度:",h," 通知栏高度:" + l);
                temp = h + l;
            }
        } catch (error) {
            console.log("获取通知栏、关闭按钮高度失败");
            temp = 44;
        }
        wrap.style.paddingTop = temp + 'px';
    },
    //自定义扫码
    async scanCodeEvent(){
        if(this.globalState){
            return;
        }
        if(!this.formData.relateOrders){
            Dialog.confirm({title: '提示',message: '请先选择单号后再进行扫码',confirmButtonText:"确定",cancelButtonText:"取消"});
            return;
        }
        const isDevelopment = process.env.NODE_ENV === 'development';
        let decodeFun = null;
        let scanCode = 'WL20250321094/PC20250329/200';
        try {
            if(!isDevelopment){
                scanCode = await window.flutter_inappwebview.callHandler('qrCode');
            }
            console.log('调用精致提供的扫码api',scanCode);
        } catch (error) {
            Dialog.confirm({title: '提示',message: '扫码异常，尝试重新打开本程序',confirmButtonText:"确定",cancelButtonText:"取消"});
            console.log("调用精致提供的扫码api",error);
            return;
        }
        try {
            decodeFun = await this.getScanCodeRuleInfo();
        } catch (error) {
            decodeFun = analysisScanCodeRules;
            console.log('请求解码规则脚本失败,错误:',error);
            console.log('请求解码规则脚本失败,即将调用本地解码函数...');
        }
        const { materialInfo, batchInfo, numInfo } = decodeFun(scanCode);
        const materialList = this.productWorkOrderMaterialInfo;  // cloneDeep(this.productWorkOrderMaterialInfo);
        console.log('当前物料信息====>',materialList);
        const filterMaterialList = materialList.filter(v => materialInfo == v.materialEntity.code);
        if(filterMaterialList.length === 0){
            Dialog.confirm({title: '提示',message: `该生产工单未包含此物料${materialInfo},请检查`,confirmButtonText:"确定",cancelButtonText:"取消"});
            return;
        }
        if(filterMaterialList.length === 1){
            filterMaterialList[0].checked = true;
            //物料是否批次
            if(filterMaterialList[0].materialEntity.isBatchMag){
                const obj = {checked:true,barCode:batchInfo,planNum:filterMaterialList[0].planAmount,realNum:numInfo,extendMap:{zhashu:""}};
                if(!batchInfo){
                    let batchCode = "";
                    try {
                        batchCode = await this.getBatchCode(this.formData.relateOrders,materialInfo);
                    } catch (error) {
                        batchCode = "CKPC20250329" + parseInt(Math.random() * 100);
                    }
                    obj.barCode = batchCode;
                }
                if(filterMaterialList[0].stockMaterialDetaiList.findIndex(v => v.barCode == batchInfo) === -1){
                    filterMaterialList[0].stockMaterialDetaiList.push(obj);
                } else {
                    const y = filterMaterialList[0].stockMaterialDetaiList.find(v => v.barCode == batchInfo);
                    y.checked = true;
                    y.planNum = filterMaterialList[0].planAmount;
                    y.realNum = Number(numInfo);
                }
                return;
            } else {
                filterMaterialList[0].realNum = Number(numInfo);
                return;
            }
        }
        if(filterMaterialList.length > 1){
            this.dialogVisible = true;
            this.dialogTableList = cloneDeep(filterMaterialList);
            this.scanInfo_tmp = { materialInfo, batchInfo, numInfo };
        }
    },
    //扫码枪扫码
    async scanCodeEvent2(res){
      if(this.globalState){
        return;
      }
      if(!this.formData.relateOrders){
        Dialog.confirm({title: '提示',message: '请先选择单号后再进行扫码',confirmButtonText:"确定",cancelButtonText:"取消"});
        return;
      }
      const isDevelopment = process.env.NODE_ENV === 'development';
      let decodeFun = null;
      let scanCode = 'WL20250321094/PC20250329/200';
      try {
        if(!isDevelopment){
          scanCode = res;
        }
        console.log('调用精致提供的扫码api',scanCode);
      } catch (error) {
        Dialog.confirm({title: '提示',message: '扫码异常，尝试重新打开本程序',confirmButtonText:"确定",cancelButtonText:"取消"});
        console.log("调用精致提供的扫码api",error);
        return;
      }
      try {
        decodeFun = await this.getScanCodeRuleInfo();
      } catch (error) {
        decodeFun = analysisScanCodeRules;
        console.log('请求解码规则脚本失败,错误:',error);
        console.log('请求解码规则脚本失败,即将调用本地解码函数...');
      }
      const { materialInfo, batchInfo, numInfo } = decodeFun(scanCode);
      const materialList = this.productWorkOrderMaterialInfo;  // cloneDeep(this.productWorkOrderMaterialInfo);
      console.log('当前物料信息====>',materialList);
      const filterMaterialList = materialList.filter(v => materialInfo == v.materialEntity.code);
      if(filterMaterialList.length === 0){
        Dialog.confirm({title: '提示',message: `该生产工单未包含此物料${materialInfo},请检查`,confirmButtonText:"确定",cancelButtonText:"取消"});
        return;
      }
      if(filterMaterialList.length === 1){
        filterMaterialList[0].checked = true;
        //物料是否批次
        if(filterMaterialList[0].materialEntity.isBatchMag){
            const obj = {checked:true,barCode:batchInfo,planNum:filterMaterialList[0].planAmount,realNum:numInfo,extendMap:{zhashu:""}};
            if(!batchInfo){
            let batchCode = "";
            try {
                batchCode = await this.getBatchCode(this.formData.relateOrders,materialInfo);
            } catch (error) {
                batchCode = "CKPC20250329" + parseInt(Math.random() * 100);
            }
            obj.barCode = batchCode;
            }
            if(filterMaterialList[0].stockMaterialDetaiList.findIndex(v => v.barCode == batchInfo) === -1){
            filterMaterialList[0].stockMaterialDetaiList.push(obj);
            } else {
            const y = filterMaterialList[0].stockMaterialDetaiList.find(v => v.barCode == batchInfo);
            y.checked = true;
            y.planNum = filterMaterialList[0].planAmount;
            y.realNum = Number(numInfo);
            }
            return;
        } else {
            filterMaterialList[0].realNum = Number(numInfo);
            return;
        }
      }
      if(filterMaterialList.length > 1){
            this.dialogVisible = true;
            this.dialogTableList = cloneDeep(filterMaterialList);
            this.scanInfo_tmp = { materialInfo, batchInfo, numInfo };
        }
    },
    completeEvent(type){
        let validateResult = false;
        this.$refs.formData.validate(result => {
            validateResult = result;
        })
        if(!validateResult){
            Dialog.confirm({title: '提示',message: "请将基本信息填写完整",confirmButtonText:"确定",cancelButtonText:"取消"});
            return;
        }

        //获取最新物料信息
        const materialList = cloneDeep(this.productWorkOrderMaterialInfo);
        //检查物料相关信息
        const list = cloneDeep(this.productWorkOrderMaterialInfo).filter(v => v.checked);
        if(list.length === 0){
            Dialog.confirm({title: '提示',message: "未选择任何物料信息",confirmButtonText:"确定",cancelButtonText:"取消"});
            return;
        }
        let checkedResult = true;
        let messageTip = "";
        for(let i = 0; i < list.length; i ++){
            const t = list[i];
            const isBatchMag = t.materialEntity.isBatchMag;
            const materialCode = t.materialEntity.code;
            const materialName = t.materialEntity.name;
            if(isBatchMag){
                const a = t.warehouseInfo.warehouseId;
                const b = t.stockMaterialDetaiList.filter(v => v.checked && v.realNum && v.barCode);
                if(!a){
                    checkedResult = false;
                    messageTip = `物料${materialName}未填写仓库信息`;
                    break;
                }
                if(b.length === 0){
                    checkedResult = false;
                    messageTip = `物料${materialName}未填写批次实际入库数量/批号`;
                    break;
                }
            } else {
                const a = t.realNum;
                const b = t.warehouseInfo.warehouseId;
                if(!a){
                    checkedResult = false;
                    messageTip = `物料${materialName}未填写实际数量`;
                    break;
                }
                if(!b){
                    checkedResult = false;
                    messageTip = `物料${materialName}未填写仓库信息`;
                    break;
                }
            }
        }
        if(!checkedResult){
            Dialog.confirm({title: '提示',message: messageTip,confirmButtonText:"确定",cancelButtonText:"取消"});
            return;
        }
        const filterMaterialList = materialList.filter(v => v.checked);
        for(let j = 0; j < filterMaterialList.length; j++){
            const t = filterMaterialList[j];
            const materialCode = t.materialEntity.code;
            const isBatchMag = t.materialEntity.isBatchMag;
            const realNum = t.realNum;
            const warehouseId = t.warehouseInfo.warehouseId;
            const batchList = t.stockMaterialDetaiList.filter(l => l.checked);
            t.stockMaterialDetaiList = batchList;
        }
        const tmp = filterMaterialList.map(v => {
            const isBatchMag = v.materialEntity.isBatchMag;
            let actualAmount = 0;
            const warehouseInfo = v.warehouseInfo.warehouseList.find(k => k.warehouseId == v.warehouseInfo.warehouseId);
            if(isBatchMag){
                actualAmount = v.stockMaterialDetaiList.reduce((pre,cur) => pre + Number(cur.realNum),0);
            } else {
                actualAmount = v.realNum;
            }
            return {
                actualAmount: actualAmount,
                planAmount: v.planAmount,
                code: v.materialEntity.code,
                productCode: v.materialEntity.code,
                warehouseId: warehouseInfo.warehouseId,
                warehouseCode: warehouseInfo.warehouseCode,
                warehouseManager: this.formData.applyPerson,
                managerPhone: this.formData.personPhone,
                stockMaterialDetaiList:v.stockMaterialDetaiList,
                extendMap:v.extendMap,
                materialRemark:v.materialRemark
            }
        })
        const { orderNumber,relateTypeName,relateType,relateOrders,planTime,applyPerson,personPhone,provideCompanyCode,provideCompany, id, state,packagePerson,inspection } = this.formData;
        const parameter = {
            inOrOutType: "workOrderComplete",
            orderNumber: orderNumber,
            planTime: planTime,
            relateType: relateType,
            relateOrders: relateOrders,
            supplierCode: provideCompanyCode,
            supplierName: provideCompany,
            createBy: applyPerson,
            applyPerson: applyPerson,
            personPhon: personPhone,
            materialDetails:tmp,
            id:id,
            state: type == 'save' ? state : 2,
            ext:{
                fieldEight:packagePerson,
                fieldNine:inspection
            }
        }
        if(type == 'save'){
            this.saveLoading = true;
        }
        if(type == 'complete'){
            this.completeLoading = true;
        }
        reqUpdateProductOrder(parameter).then(response => {
            if(response.code === 200){
                Dialog.confirm({title: '提示',message: '保存成功',confirmButtonText:"确定",cancelButtonText:"关闭"}).then(confirm => {
                    //跳转首页
                    this.$router.push("/productInventory");
                },cancel => {
                    //跳转首页
                    this.$router.push("/productInventory");
                })
                //清空缓存
                this.CLEAR_PURCHASE_EDIT_INFO_CACHE();
            }
            this.completeLoading = false;
            this.saveLoading = false;
            console.log('更新采购入库单api',response);
        },error => {
            const msg = error.response.data.message || "请求失败，请稍后重试";
            Dialog.confirm({title: '提示',message: msg,confirmButtonText:"确定",cancelButtonText:"关闭"});
            console.log('更新采购入库单api',error);
            this.completeLoading = false;
            this.saveLoading = false;
        })
    },
    //查询仓库信息
    getWareHouseInfo(){
      reqWarehouseList().then(response => {
        if(response.code === 200){
          this.warehouseList = response.data.map(e => {
            return {
              warehouseCode:e.warehouseCode,
              warehouseName:e.warehouseName,
              warehouseId:e.warehouseId,
              warehouseType:e.warehouseType
            }
          })
        }
        console.log('请求仓库列表信息',response);
      },error => {
        console.log('请求仓库列表信息',error);
      })
    },
    setCacheData(cacheData){
        console.log('获取缓存信息====>',cacheData);
        if(cacheData === null){
            return ;
        }
        const { defaultOrderNum,relateOrders,planTime,applyPerson,provideCompany,id,orderState,relateType,inspection } = cacheData;
        if(defaultOrderNum){
            this.formData.orderNumber = defaultOrderNum;
        }
        if(relateOrders){
            this.formData.relateOrders = relateOrders;
        }
        if(planTime){
            this.formData.planTime = planTime;
        }
        if(applyPerson.applyPersonName){
            this.formData.nickname = applyPerson.applyPersonName;
            this.formData.applyPerson = applyPerson.applyPerson;
            this.formData.personPhone = applyPerson.personPhone;
        }
        if(provideCompany.supplierCode){
            this.formData.provideCompany = provideCompany.supplierName;
            this.formData.provideCompanyCode = provideCompany.supplierCode;
        }
        if(id){
            this.formData.id = id;
        }
        if(String(orderState).length !== 0){
            this.formData.state = orderState;
        }
        if(relateType){
            this.formData.relateType = relateType;
            this.formData.relateTypeName = this.relateList.find(v => v.value == relateType)?.label;
        }
        if(inspection){
            this.formData.inspection = inspection;
        }
        if(cacheData.package){
            this.formData.packagePerson = cacheData.package;
        }
        console.log(orderState,'===');
    },
    //获取解码规则脚本
    getScanCodeRuleInfo(){
        return new Promise((resolve,reject) => {
            reqScanCodeRuleInfo().then(response => {
                if(response.code == 200 && response.data){
                    const functionStr = response.data.value;
                    const fun = new Function('return ' + functionStr);
                    resolve(fun());
                }
                console.log('获取解码规则脚本api',response);
            },error => {
                console.log('获取解码规则脚本api',error);
                reject(new Error("请求解码规则脚本失败"));
            })
        })
    },
    //自动生成批次号
    getBatchCode(relateOrders,materialCode){
        return new Promise((resolve,reject) => {
            reqBarcode(relateOrders,materialCode).then(response => {
                if(response.code === 200){
                    resolve(response.data[0])
                }
            },error => {
                console.log('自动生成批次号api',error);
                reject();
            })
        })
    },
    printEvent(item){
        this.printMaterialInfo = item;
        this.printMaterialInfo.relateOrders = this.formData.relateOrders;
        this.isPrintShow = true;
    },
    handleConfirmPrint(){
        const isDevelopment = process.env.NODE_ENV === "development";
        if(!isDevelopment){
            this.isPrintShow = false;
            this.printMaterialInfo = null;
        }
        console.log('print confirm');
    },
    handleCancelPrint(){
        this.isPrintShow = false;
        this.printMaterialInfo = null;
        console.log('print cancel');
    },
    packageConfirm(val){
        const { id,username,nickname } = val;
        this.formData.packagePerson = nickname;
        this.set_cache_package(nickname);
        this.packageShow = false;
    },
    inspectionConfirm(val){
        const { id,username,nickname } = val;
        this.formData.inspection = nickname;
        this.set_cache_inspection(nickname);
        this.inspectionShow = false;
    },
    getPackageList(){
        reqPackageList().then(response => {
            if(response.code == 200 && response.data){
                const list = response.data;
                const tmp = list.map(val => {
                    return {
                        id:val.id,
                        nickname:val.nickname,
                        username:val.username
                    }
                })
                this.packageList = tmp;
            }
            console.log("请求包装员列表api",response);
        }, error => {
            console.log("请求包装员列表api",error);
        })
    },
    getInspectionList(){
        reqInspectionList().then(response => {
            if(response.code == 200 && response.data){
                const list = response.data;
                const tmp = list.map(val => {
                    return {
                        id:val.id,
                        nickname:val.nickname,
                        username:val.username
                    }
                })
                this.inspectionList = tmp;
            }
            console.log("请求全检员列表api",response);
        }, error => {
            console.log("请求全检员列表api",error);
        })
    },
    handleSelectionChange(val) {
      if (val.length > 1) {
        this.$nextTick(() => {
          this.selectedRow = val.pop();
          this.dialogTableList.forEach(row => {
            this.$refs.dialogTable.toggleRowSelection(row, row === this.selectedRow);
          });
        });
      } else {
        this.selectedRow = val.length ? val[0] : null;
      }
    },
    async dialogTableConfirm(){
        const selected = this.selectedRow;
        const { materialInfo, batchInfo, numInfo } = this.scanInfo_tmp;
        const materialList = this.purchaseOrderInfoList;
        const filterMaterialList = materialList.filter(v => v.rowIndex == selected.rowIndex);
        this.dialogVisible = false;
        if(filterMaterialList.length > 0){
            filterMaterialList[0].checked = true;
            //物料是否批次
            if(filterMaterialList[0].materialEntity.isBatchMag){
                const obj = {checked:true,barCode:batchInfo,planNum:filterMaterialList[0].planAmount,realNum:numInfo,extendMap:{zhashu:""}};
                if(!batchInfo){
                    let batchCode = "";
                    try {
                        batchCode = await this.getBatchCode(this.formData.relateOrders,materialInfo);
                    } catch (error) {
                        batchCode = "CKPC20250329" + parseInt(Math.random() * 100);
                    }
                    obj.barCode = batchCode;
                }
                if(filterMaterialList[0].stockMaterialDetaiList.findIndex(v => v.barCode == batchInfo) === -1){
                    filterMaterialList[0].stockMaterialDetaiList.push(obj);
                } else {
                    const y = filterMaterialList[0].stockMaterialDetaiList.find(v => v.barCode == batchInfo);
                    y.checked = true;
                    y.planNum = filterMaterialList[0].planAmount;
                    y.realNum = Number(numInfo);
                }
                return;
            } else {
                filterMaterialList[0].realNum = Number(numInfo);
                return;
            }
        }
    }
  }
}
</script>

<style lang="scss" >
.scan-img{
  position: fixed;
  bottom: 8vh;
  right: 0;
  // transform: translateX(-50%);
  width: 82px;
  height: 82px;
  z-index: 2;
}
.add-wrap{
    .el-form-item__error{
        position: absolute !important;
        top: 25px;
        right: 30px;
    }
    .el-textarea__inner{
        border: none !important;
        text-align: right !important;
    }
}
</style>
<style lang="scss" scoped>
.header-top{
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    z-index: 2;
}
.add-wrap{
    padding-top: 44px;
    padding-bottom: 80px;
    .form-box{
        margin: 12px 12px 0;
        background-color: #ffffff;
        border-radius: 4px;
        .el-form-item{
            margin-bottom: 0 !important;

        }
        .form-title{
            font-size: 16px;
            margin: 0 7px;
            height: 40px;
            display: flex;
            align-items: center;
            border-bottom: 1px #F3F3F3 solid;
            position: relative;
            padding-left: 8px;
            &::before{
                content: '';
                width: 4px;
                height: 14px;
                background-color: #548AF1;
                position: absolute;
                left: 0;
                top: 13px;
            }
        }
        .form-item{
            margin: 0 7px;
            padding: 0 7px;
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            border-bottom: 1px #F3F3F3 dotted;
            font-size: 13px;
            color: #333333;
            .label{
                display: flex;
                align-items: center;
                .required{
                    content: '';
                    color: #FF0000;
                    display: inline-block;
                    width: 6px;
                    height: 6px;
                    background: url('../../assets/images/required.png') no-repeat;
                    background-size: 100% 100%;
                    margin-right: 4px;
                }
                .scan{
                    width: 19px;
                    height: 19px;
                    margin-left: 9px;
                }
            }
            .info-wrap{
                text-align: right;
                .code{
                    color: #548AF1;

                }
            }
            input{
                width: 100%;
                border: none;
                text-align: right;
            }
            .select-wrap{
                color: #999999;
                .val{
                    color: #333333;
                }
                i{
                    margin-left: 5px;
                    color: #909090;
                }
            }
        }
        .remark-wrap{
            padding: 6px 0;
            .textarea{
                // height: 35px;
                width: 100%;
                border: none;
                font-size: 14px;
                color: #333333;

            }
        }
    }
    .material-box{
        margin: 12px 12px 0;
        background-color: #ffffff;
        border-radius: 4px;
        .item-title{
            font-size: 16px;
            margin: 0 7px;
            height: 40px;
            display: flex;
            align-items: center;
            border-bottom: 1px #F3F3F3 solid;
            position: relative;
            padding-left: 8px;
            &::before{
                content: '';
                width: 4px;
                height: 14px;
                background-color: #548AF1;
                position: absolute;
                left: 0;
                top: 13px;
            }
        }
        .box-content{
            width: 100%;
            height: 350px;
            overflow: auto;
            .cell-desc-title{
                font-size:14px;
                font-weight: normal;
            }
            .cell-desc-scan{
                width: 19px;
                height: 19px;
            }
        }
    }
}
.model-footer-wrap{
    width: 100%;
    display: flex;
    .save-btn{
        flex:1;
        margin-right: 10px;
    }
    .complete-btn{
        flex:3;
    }
}
.van-action-sheet .content{
    width: 100%;
    height: 250px;
    padding:16px 16px 160px;
    overflow: auto;
    .content-item{
        width:100%;
        height: 50px;
        margin-bottom: 10px;
        display: flex;
        flex-wrap: wrap;
        .item-span1{
            font-size: 12px;
            padding: 0px 15px;
        }
        .item-span2{
            font-size: 12px;
            padding: 0px 15px;
        }
        .item-span3{
            font-size:12px;
            padding: 0px 15px;
        }
    }
}
</style>
